package com.kdzy.lshy.socity_server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kdzy.lshy.socity_server.common.*;
import com.kdzy.lshy.socity_server.repository.BaseDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 意见反馈Service
 * @author hzj
 * @since 2018-09-04
 */
@Service
public class FeedbackService extends BaseService {

    private static final Logger logger = LoggerFactory.getLogger(WechartService.class);

    @Resource
    private BaseDao baseDao;


    /**
     * 保存意见反馈
     *
     * @param param
     * @param request
     * @return
     */
    public Object saveFeedback(String param, HttpServletRequest request) {

        LinkedHashMap<Object, Object> map = null;

        if (StringUtils.isNoneBlank(StringUtils.trim(param))) {
            // 1.解析json数据
            JSONObject jsonObject = JSON.parseObject(param);

            String socityId = jsonObject.getString("socity_id");//社区id
            String dwellerId = jsonObject.getString("dweller_id");//居民ID
            String feedTitle = jsonObject.getString("feed_title");//反馈标题
            String feedMessage = jsonObject.getString("feed_message");//反馈内容
            String feedName = jsonObject.getString("feed_name");//反馈人姓名

            String feedPhoto = jsonObject.getString("feed_photo");//反馈图片地址

            Long stamp = jsonObject.getLong("stamp"); // 时间戳
            Integer  version = jsonObject.getInteger("version"); // 数据版本 0:测试 1:生产
            Integer visitType = jsonObject.getInteger("visit_type"); // 访问类型 0:测试 1:生产
            Integer visitPlat = jsonObject.getInteger("visit_plat"); // 访问平台 0:网页 1:一体机 2:小程序 3:其他
            Integer isUsed = jsonObject.getInteger("is_used"); // 是否有效 0:有效 1:无效

            //String note = jsonObject.getString("note");//备注

            // 参数非空判断      //一体机（1）居民ID可为空 但必填反馈人姓名    网页及APP可不填反馈姓名
            if (visitPlat==null) {
                logger.info("参数 visitPlat 为空!");
                map = ResultMap.creatReault("88", "失败", "visitPlat参数为空");
                logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            } else {
                if (visitPlat == 1 && (StringUtils.isBlank(StringUtils.trim(feedName)))) {
                    logger.info("一体机上反馈人姓名为空！");
                    map = ResultMap.creatReault("88", "失败", "一体机上feedName参数为空");
                    logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                    return map;
                }
            }
            if ((visitPlat == 0) || (visitPlat  == 3) ) { //网页及app上居民ID不能为空
                if (dwellerId==null) {
                    logger.info("参数 dwellerId 为空!");
                    map = ResultMap.creatReault("88", "失败", "dwellerId参数为空");
                    logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                    return map;
                }

                // 根据居民id查询居民姓名
                String findNameSql = "SELECT dw.dweller_name dwellerName FROM dweller dw WHERE dw.ID = '"+dwellerId+"'";
                List<Map<String, Object>> list = baseDao.queryForList(findNameSql);
                if (list != null && list.size() > 0) {
                    feedName = (String) list.get(0).get("dwellerName");
                }
            } else if (visitPlat == 1) { // 一体机
                dwellerId = ""; // 置空
            }
            if (socityId==null) {
                logger.info("参数 socityId 为空!");
                map = ResultMap.creatReault("88", "失败", "socityId参数为空");
                logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }

            if (feedTitle==null) {
                logger.info("参数 feedTitle 为空!");
                map = ResultMap.creatReault("88", "失败", "feedTitle参数为空");
                logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (feedMessage == null) {
                logger.info("参数 feedMessage 为空!");
                map = ResultMap.creatReault("88", "失败", "feedMessage参数为空");
                logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (stamp == null) {
                logger.info("参数 stamp 为空!");
                map = ResultMap.creatReault("88", "失败", "stamp参数为空");
                logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (version == null) {
                logger.info("参数 version 为空!");
                map = ResultMap.creatReault("88", "失败", "version参数为空");
                logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (isUsed == null) {
                logger.info("参数 isUsed 为空!");
                map = ResultMap.creatReault("88", "失败", "isUsed参数为空");
                logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }


            String systoken = null;
            if (!(jsonObject.getInteger("visit_plat") != 0)) { // 网页端
                systoken = jsonObject.getString("systoken"); // 全局token
                if (StringUtils.isBlank(systoken)) {
                    logger.info("systoken为空");
                    map = ResultMap.creatReault("33", "失败", "token为空");
                    logger.info("出去保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                    return map;
                }
            }

            String officerId = null;
            if (jsonObject.getInteger("visit_plat") == 0) { // 网页端

                // 根据身份证从redis中获取token
                Jedis jedis = new Jedis("140.143.210.101", 6379);
                jedis.auth("q1w2e3r4t5");

                List<String> infoList = jedis.hmget(systoken, "systoken", "officerId");
                String systokenRedis = null;
                if (infoList != null && infoList.size() > 0) {
                    systokenRedis = infoList.get(0); // token
                    officerId = infoList.get(1); // 用户id
                }

                // 查看token是否过期
                if (StringUtils.isBlank(systokenRedis)) { // 重新登录，弹出登录框
                    logger.info("全局systoken过期，需要重新获取systoken");
                    map = ResultMap.creatReault("33", "失败", "systoken过期");
                    logger.info("出去 保存意见反馈 saveFaceback()方法；；出参 = " + JSON.toJSONString(map));
                    return map;
                }

                // token不一致
                if (!StringUtils.equals(systokenRedis, systoken)) {
                    logger.info("用户访问的token不一致");
                    map = ResultMap.creatReault("331", "失败", "systoken不一致");
                    logger.info("出去保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                    return map;
                }

            }

            String FaceBackID = UUID.randomUUID().toString().replace("-", ""); // faceback表主键;
            String createTime = DateUtil.format(new Date(stamp), "yyyy-MM-dd HH:mm:dd"); // 更新时间yyyy-MM-dd HH:mm:ss

            // 将此次登录录入居民微信表中
            String updateFaceBackSql = "INSERT INTO \n" +
                    "\tfeedback (\n" +
                    "\t\tID,\n" +
                    "\t\tsocity_id,\n" +
                    "\t\tdweller_id,\n" +
                    "\t\tfeed_title,\n" +
                    "\t\tfeed_message,\n" +
                    "\t\tfeed_photo,\n" +
                    "\t\tfeed_name,\n" +
                    "\t\tcreate_time,\n" +
                    "\t\tstamp,\n" +
                    "\t\tversion,\n" +
                    "\t\tvisit_plat,\n" +
                    "\t\tvisit_type,\n" +
                    "\t\tis_used\n" +
                    "\t)\n" +
                    "VALUES\n" +
                    "\t(\n" +
                    "\t\t'" + FaceBackID + "',\n" +
                    "\t\t'" + socityId + "',\n" +
                    "\t\t'" + dwellerId + "',\n" +
                    "\t\t'" + feedTitle + "',\n" +
                    "\t\t'" + feedMessage + "',\n" +
                    "\t\t'" + feedPhoto + "',\n" +
                    "\t\t'" + feedName + "',\n" +
                    "\t\t'" + createTime + "',\n" +
                    "\t\t'" + stamp + "',\n" +
                    "\t\t'" + version + "',\n" +
                    "\t\t'" + visitPlat + "',\n" +
                    "\t\t'" + visitType + "',\n" +
                    "\t\t'" + isUsed + "'\n" +
                    "\t)\t";

            int facebackupdate = baseDao.update(updateFaceBackSql);


            if (facebackupdate <= 0) {
                logger.info("更新表 faceback 失败");
                map = ResultMap.creatReault("77", "失败", "数据库操作失败");
                logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }

            map = ResultMap.creatReault("66", "成功", "意见反馈添加成功");
            map.put("FaceBackID", FaceBackID);
            logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
            return map;

        } else {
            logger.info("param为空");
            map = ResultMap.creatReault("88", "失败", "参数为空");
        }

        logger.info("出去 保存意见反馈 saveFaceback()方法；出参 = " + JSON.toJSONString(map));
        return map;

    }


    /**
     * 根据条件进行模糊查询(可根据反馈标题，反馈内容，反馈人姓名，反馈时间)
     *
     * @param param
     * @param request
     * @return
     */
    public Object selectFeedback(String param, HttpServletRequest request) {

        LinkedHashMap<Object, Object> map = null;

        if (StringUtils.isNoneBlank(StringUtils.trim(param))) {
            // 1.解析json数据
            JSONObject jsonObject = JSON.parseObject(param);

            String feedTitle = jsonObject.getString("feed_title");//反馈标题
            String feedMessage = jsonObject.getString("feed_message");//反馈内容
            String feedName = jsonObject.getString("feed_name");//反馈人姓名
            String dwellerIdcard = jsonObject.getString("dweller_idcard");//居民身份证

            String visitType = jsonObject.getString("visit_type");//访问类型
            String version = jsonObject.getString("version"); // 数据版本 0:测试 1:生产
            String visitPlat = jsonObject.getString("visit_plat"); // 访问平台 0:网页 1:一体机 2:小程序 3:其他
            String isUsed = jsonObject.getString("is_used"); // 是否有效 0:有效 1:无效


            String systoken = null;
            if (!(jsonObject.getInteger("visit_plat") != 0)) { // 网页端
                systoken = jsonObject.getString("systoken"); // 全局token
                if (StringUtils.isBlank(systoken)) {
                    logger.info("systoken为空");
                    map = ResultMap.creatReault("33", "失败", "token为空");
                    logger.info("出去保存意见反馈 selectFaceback()方法；出参 = " + JSON.toJSONString(map));
                    return map;
                }
            }

            String officerId = null;
            if (jsonObject.getInteger("visit_plat") == 0) { // 网页端

                // 根据身份证从redis中获取token
                Jedis jedis = new Jedis("140.143.210.101", 6379);
                jedis.auth("q1w2e3r4t5");

                List<String> infoList = jedis.hmget(systoken, "systoken", "officerId");
                String systokenRedis = null;
                if (infoList != null && infoList.size() > 0) {
                    systokenRedis = infoList.get(0); // token
                    officerId = infoList.get(1); // 用户id
                }

                // 查看token是否过期
                if (StringUtils.isBlank(systokenRedis)) { // 重新登录，弹出登录框
                    logger.info("全局systoken过期，需要重新获取systoken");
                    map = ResultMap.creatReault("33", "失败", "systoken过期");
                    logger.info("出去 保存意见反馈 selectFaceback()方法；；出参 = " + JSON.toJSONString(map));
                    return map;
                }

                // token不一致
                if (!StringUtils.equals(systokenRedis, systoken)) {
                    logger.info("用户访问的token不一致");
                    map = ResultMap.creatReault("331", "失败", "systoken不一致");
                    logger.info("出去保存意见反馈 selectFaceback()方法；出参 = " + JSON.toJSONString(map));
                    return map;
                }
            }


            if (version == null) {
                logger.info("参数 version 为空!");
                map = ResultMap.creatReault("88", "失败", "version参数为空");
                logger.info("出去 保存意见反馈 selectFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (visitPlat == null) {
                logger.info("参数 visitPlat 为空!");
                map = ResultMap.creatReault("88", "失败", "visitPlatn参数为空");
                logger.info("出去 保存意见反馈 selectFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (isUsed == null) {
                logger.info("参数 isUsed 为空!");
                map = ResultMap.creatReault("88", "失败", "isUsed参数为空");
                logger.info("出去 保存意见反馈 selectFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }
            if (visitType == null) {
                logger.info("参数 visitType 为空!");
                map = ResultMap.creatReault("88", "失败", "visitType参数为空");
                logger.info("出去 保存意见反馈 selectFaceback()方法；出参 = " + JSON.toJSONString(map));
                return map;
            }

            String selectSQL = "SELECT\n" +
                    "\tf.*,\n" +
                    "\td.dweller_idcard dweller_idcard\n" +
                    "FROM\n" +
                    "\tfeedback f\n" +
                    "LEFT JOIN dweller d ON f.dweller_id = d.ID where 1=1 ";

            StringBuilder SQL = new StringBuilder(selectSQL);
            List<Object> tags = new ArrayList<Object>();


            //办事员数据版本
            if (StringUtils.isNoneBlank(StringUtils.trim(version))) {
                SQL.append(" and f.version = \t ? \t");
                tags.add(version);
            }
            //预约数据是否使用
            if (StringUtils.isNoneBlank(StringUtils.trim(isUsed))) {
                SQL.append(" and f.is_used = \t ? \t");
                tags.add(isUsed);
            }
            //访问平台
            if (StringUtils.isNoneBlank(StringUtils.trim(visitType))){
                SQL.append(" and f.visit_type = \t ? \t");
                tags.add(visitType);
            }

            //根据反馈人姓名、反馈标题、反馈内容、反馈时间进行模糊查询   身份证进行精确查询
            if (StringUtils.isNoneBlank(StringUtils.trim(dwellerIdcard))) {
                SQL.append("and d.dweller_idcard = ? \t");
                tags.add(dwellerIdcard);
            }
            if (StringUtils.isNoneBlank(StringUtils.trim(feedTitle))) {
                SQL.append(" and f.feed_title like ? \t");
                tags.add("%" + feedTitle + "%");
            }
            if (StringUtils.isNoneBlank(StringUtils.trim(feedMessage))) {
                SQL.append(" and f.feed_message like ?\t");
                tags.add("%" + feedMessage + "%");
            }
            if (StringUtils.isNoneBlank(StringUtils.trim(feedName))) {
                SQL.append(" and f.feed_name like ?\t");
                tags.add("%" + feedName + "%");
            }

            SQL.append(" order by f.create_time desc");

            //查询总条数
            String countsql = "select count(1) as count from (\n" + SQL.toString() + "\n) as t";
            long count = 0;
            try {
                count = baseDao.getCount(countsql, tags);
            } catch (Exception e) {
                logger.info("后台处理异常，异常信息1：" + ExceptionDetailMessage.getExceptionDetail(e));
                logger.info("总条数统计出错");
                map = ResultMap.creatReault("77", "失败", "数据库操作失败");
                return map;
            }

            //分页
            Integer page = Integer.valueOf(request.getParameter("offset"));
            Integer rows = Integer.valueOf(request.getParameter("limit"));

            SQL.append(" limit " + page + "," + rows + "");

            Object content = baseDao.queryForList(SQL.toString(), tags.toArray());

            map = ResultMap.creatReault(Constants.http_status_success, Constants.http_info_success, content);
            map.put("total", count);
            logger.info("出去 查询用户反馈 selectFeedService()方法；出参 = " + JSON.toJSONString(map));
            return map;

        } else {
            logger.info("param为空");
            map = ResultMap.creatReault("88", "失败", "param参数为空");
        }

        logger.info("出去 保存意见反馈 selectFaceback()方法；出参 = " + JSON.toJSONString(map));
        return map;
    }

}